package top.peng.project.example.chapter25;

import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author tanpeng
 * @date 2019/4/22 11:17
 * @desc 测试ajax轮询心跳检测
 */
@RestController
public class AjaxPollingHeartCheckController {

    // 保存所有任务的容器
    public static final List<String> listTaskId = new CopyOnWriteArrayList<>();

    @GetMapping(value = "/check-task")
    public String checkTask(String taskId) {
        Boolean status = listTaskId.contains(taskId);
        String result = "{'flag': " + status + ", 'l': " + listTaskId.size() + "}";
        Map<String, Object> mapResult = new HashMap();
        mapResult.put("flag", status);
        mapResult.put("l", Integer.valueOf(listTaskId.size()));

        return JSON.toJSONString(mapResult);
    }

    @GetMapping(value = "/task")
    public String task() {
        final String uuid = UUID.randomUUID().toString();
        listTaskId.add(uuid);
        // 注意，一定要记得调用start()方法，启动线程
        // 我这里忘了调用start()方法，困惑我一大早上 -_-!
        new Thread(() -> {
            try {
                // 模拟处理数据，耗时8秒
                Thread.sleep(8000);
                listTaskId.remove(uuid);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();// start()启动线程

        return JSON.toJSONString(new HashMap<String, Object>(){{put("flag", true); put("taskId", uuid);}});
    }

}
